package friend

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"practice/config"
	"practice/internal/model/dao"
)

type Friend struct {
	Mobile string `form:"mobile" json:"mobile" xml:"mobile"  binding:"required,mobile"`
	Name   string `form:"name" json:"name" xml:"name" binding:"required"`
	Note   string `form:"note" json:"note" xml:"note"`
	Group  int    `form:"group" json:"group" xml:"group"`
}

func FriendAdd(c *gin.Context) {
	var json Friend
	if err := c.ShouldBindJSON(&json); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	mobile := json.Mobile
	name := json.Name
	note := json.Note
	group := json.Group
	var detail dao.UserDetail
	config.DB.Where("mobile = ? or name = ?", mobile, name).First(&detail)
	if detail.ID == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "没有该用户"})
		return
	}
	var friend2 dao.Friends
	config.DB.Where("mobile=?", mobile).Limit(1).Find(&friend2)
	if friend2.ID != 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "该好友已存在"})
		return
	}
	fmt.Println(friend2)
	value, _ := c.Get("userId")
	a := value.(uint)
	friends := dao.Friends{
		UserId: int(a),
		Note:   note,
		Name:   detail.Name,
		Mobile: detail.Mobile,
		Email:  detail.Email,
		Group:  int8(group),
	}
	config.DB.Create(&friends)
	c.JSON(http.StatusOK, gin.H{
		"msg":  "添加成功",
		"data": friends.ID,
	})
}
